<template>
  <el-dialog
    v-model="showDialog"
    :title="title"
    :append-to-body="true"
    :width="width"
    @closed="closeDialog"
    destroy-on-close
    :close-on-click-modal="false"
  >
    <super-form
      :formAndTable="false"
      ref="protocolRef"
      v-bind="formProtocolConfig"
      :modelValue="formData"
      :rules="formDataRule"
    />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closeDialog(false)"> 取 消 </el-button>
        <el-button type="primary" :loading="loading" @click.stop="handleSubmit" @keyup.enter="keyDown">
          确 定
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref } from "vue";
import { type FormRules } from "element-plus";
import SuperForm from "@/components/SuperForm/index.vue";
import { formProtocolConfig } from "./formConfig";
interface Props {
  width?: number; // 宽度
  title?: string; // 标题
  data?: any; // 接受的数据
  type: string; // 类型
}
const { width = 600, title, data, type } = defineProps<Props>();

const emits = defineEmits<{
  handleSubmit: [_row: any];
  handleClose: any;
}>();
// 弹窗
const showDialog = ref<boolean>(false);
const loading = ref<boolean>(false);
const protocolRef = ref<any>();
// 新增
let formData = ref<any>({
  name: "",
});
// 校验
const formDataRule: FormRules = {
  name: [{ required: true, message: "请输入名称", trigger: "change" }],
};
watch(
  () => data?.id,
  (olden) => {
    if (olden) {
      console.log(olden, "olden");
      Object.assign(formData.value, { ...data });
    }
  },
  {
    deep: true,
  }
);
// 表单提交
const handleSubmit = (): void => {
  protocolRef.value.ruleFormRef.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      if (type === "edit") {
        ElMessage.success("编辑成功");
        closeDialog(true);
      }
    }
  });
};
// 键盘事件
const keyDown = (e: any) => {
  if (e.keyCode === 13) {
    handleSubmit();
  }
};
// 关闭
const closeDialog = (isClose?: boolean | undefined): void => {
  showDialog.value = false;
  emits("handleClose", isClose);
  window.removeEventListener("keydown", keyDown, false);
  formData.value = {
    name: "",
  };
};
// 打开
const openDialog = (): void => {
  showDialog.value = true;
  loading.value = false;
  nextTick(() => {
    window.addEventListener("keydown", keyDown);
  });
};
defineExpose({
  closeDialog,
  openDialog,
});
</script>
